from src.vobjects.video import Video

from src.database import Database

from plugins.core.pluginvideo import PluginVideo

import json

class History:

    def __init__(self):
        self.database   = Database()
        self.video_list = []
        self._id_list   = []
        self.load_history()

    def load_history(self):
        for item in self.database.load_history():
            try:
                item_text = item[0].replace("\"", "`")
                item_text = item_text.replace("\'", "\"")
                dct = json.loads(item_text)
                if not 'url' in dct.keys():
                    video = Video().from_history_dict(dct)
                    if not video.videoId in self._id_list:
                        self.video_list.append(video)
                        self._id_list.append(video.videoId)
                else:
                    video = PluginVideo().from_history_dict(dct)
                    if not video.url in self._id_list:
                        self.video_list.append(video)
                        self._id_list.append(video.url)

            except: continue
        self.video_list.reverse()

    def insert(self, video):
        if not video.in_history(self): self.video_list.insert(0, video)
        self.database.insert_video_in_history(video.to_history_dict())

    def remove(self, video):
        self.database.delete_video_from_history(video.to_history_dict())


